package main

import (
	"fmt"
	"math/rand"
	"net/http"
	_ "net/http/pprof"
	"os"
	"pd/server/app/pd/api"
	context "pd/server/app/pd/config"
	"pd/server/com"
	"pd/server/plugin/logger"
	"time"

	"github.com/sirupsen/logrus"
	"github.com/urfave/cli"
)

func init() {
	rand.Seed(time.Now().UnixNano())
}

var version = "development"

func BackgroundService(conf *context.Config) {
}

func main() {
	go func() {
		logger.Info(http.ListenAndServe(":8781", nil))
	}()

	app := cli.NewApp()
	app.Name = "PD System"
	app.Usage = "轻松派"
	app.Version = version
	app.Copyright = "(c) 2018 Doudouyun <doudouyun.com>"
	app.EnableBashCompletion = true

	app.Flags = []cli.Flag{
		cli.BoolFlag{
			Name:   "debug",
			Usage:  "run in debug mode",
			EnvVar: "JT_AUTH_DEBUG",
		},
		cli.StringFlag{
			Name:   "config, c",
			Usage:  "load configuration from `FILENAME`",
			Value:  "",
			EnvVar: "JT_AUTH_CONFIG_FILE",
		},
		cli.IntFlag{
			Name:   "api-port, p",
			Usage:  "HTTP server port",
			Value:  8301,
			EnvVar: "JT_AUTH_API_PORT",
		},
	}

	app.Action = StartCommand.Action

	app.Run(os.Args)

}

// Starts web server (user interface)
var StartCommand = cli.Command{
	Name:   "start",
	Usage:  "Starts web server",
	Flags:  startFlags,
	Action: startAction,
}

var startFlags = []cli.Flag{
	cli.IntFlag{
		Name:   "api-port, p",
		Usage:  "api server port",
		Value:  8301,
		EnvVar: "API_PORT",
	},
	cli.StringFlag{
		Name:   "api-host, i",
		Usage:  "api server host",
		Value:  "",
		EnvVar: "API_HOST",
	},
	cli.StringFlag{
		Name:   "api-mode, m",
		Usage:  "debug, release or test",
		Value:  "",
		EnvVar: "API_MODE",
	},
}

func startAction(ctx *cli.Context) error {
	conf := context.NewConfig(ctx)

	if conf.ApiPort() < 1 {
		logrus.Fatal("Server port must be a positive integer")
	}

	fmt.Printf("Starting api server at %s:%d...\n", conf.ApiHost(), conf.ApiPort())

	if conf.IsLocal() {
		logger.Info("is set to local")
		com.SetLocal(conf.IsLocal())
	}

	BackgroundService(conf) // 后台服务

	api.Start(conf)

	fmt.Println("Done.")

	return nil
}
